#include "widgetanchor.h"

WidgetAnchor::WidgetAnchor(QWidget* pWidget, QQuickItem* pItem)
    : QObject(pWidget),
      _pWidget(pWidget),
      _pQuickItem(pItem)
{
    connect(_pQuickItem, &QQuickItem::xChanged, this, &WidgetAnchor::updateGeometry);
    connect(_pQuickItem, &QQuickItem::yChanged, this, &WidgetAnchor::updateGeometry);
    connect(_pQuickItem, &QQuickItem::widthChanged, this, &WidgetAnchor::updateGeometry);
    connect(_pQuickItem, &QQuickItem::heightChanged, this, &WidgetAnchor::updateGeometry);
    connect(_pQuickItem, &QQuickItem::visibleChanged, this, &WidgetAnchor::updateVisible);
    _pWidget->hide();
    _visible = false;
}


void WidgetAnchor::updateGeometry() {


    if(!_visible) {
        _pWidget->hide();
        return;
    }
    if(!_pWidget || !_pQuickItem) return;

    _pWidget->hide();
    QTimer::singleShot(60, [this](){
        if(!_pQuickItem->isVisible()){      // 阻止visible顺序乱刷
            return;
        }

        QRectF r = _pQuickItem->mapRectToItem(nullptr, QRectF(_pQuickItem->x(), _pQuickItem->y(), _pQuickItem->width(), _pQuickItem->height()));

        r.setX(r.x()+15);
        r.setY(r.y()+50);       // 我也不知道这个偏移量是哪来的……
        _pWidget->setGeometry(r.toRect());
        _pWidget->show();
        emit sigRectChanged(_pQuickItem->x(), _pQuickItem->y(), _pQuickItem->width(), _pQuickItem->height());
    });
}

void WidgetAnchor::updateVisible(){
//    qDebug() << "Connect Visible Changed = " << _pQuickItem->isVisible();
    if(_pQuickItem->isVisible()){
        show();
    }else{
        hide();
    }
}

void WidgetAnchor::show(){

    if(!_pWidget || !_pQuickItem) return;

    _visible = true;
    updateGeometry();


}

void WidgetAnchor::hide(){

    if(!_pWidget || !_pQuickItem) return;

    _visible = false;
    updateGeometry();

}
